package com.taofuxn.admin.api.controller.sys;

import com.taofuxn.admin.api.config.CurrentUser;
import com.taofuxn.admin.api.controller.common.BaseController;
import com.taofuxn.admin.api.interceptors.NoRequestLogin;
import com.taofuxn.admin.api.model.SysUserModel;
import com.taofuxn.admin.api.model.request.LoginRequest;
import com.taofuxn.admin.api.model.response.LoginResponse;
import com.taofuxn.admin.api.model.response.SessionUserResp;
import com.taofuxn.admin.api.service.SessionService;
import com.taofuxn.admin.api.service.SysUserConfigService;
import com.taofuxn.admin.common.exception.ExceptionEnum;
import com.taofuxn.admin.common.model.BaseResults;
import com.taofuxn.admin.common.util.CopyUtils;
import com.taofuxn.admin.common.util.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;

/**
 * 登录鉴权
 */
@Api
@Slf4j
@RequestMapping("/sys/auth")
@RestController
public class LoginController extends BaseController {

    @Autowired
    private SysUserConfigService sysUserConfigService;
    @Autowired
    private SessionService sessionService;

    @ApiOperation("登录")
    @NoRequestLogin
    @PostMapping("/login")
    public BaseResults login(HttpServletRequest request,@RequestBody @Valid LoginRequest params, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return BaseResults.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUserModel user = sysUserConfigService.getUserByLoginName(params.getLoginName());
        if (null == user) {
            return BaseResults.fail(ExceptionEnum.ACCOUNT_NOT_FOUND);
        }
        if (!Objects.equals(SecurityUtil.md5(params.getPassword() ,user.getSalt()), user.getPassword())) {
            return BaseResults.fail(ExceptionEnum.PASSWORD_ERROR);
        }

        String token = sessionService.addUserSession(user);
        request.getSession().setAttribute(sessionService.USER_SESSION_KEY,user);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUser(loginResponse.transform(user));
        loginResponse.setToken(token);
        return BaseResults.success(loginResponse);
    }


    @ApiOperation("注册用户")
    @NoRequestLogin
    @PostMapping("/register")
    public BaseResults registerUser(@RequestBody @Valid LoginRequest request,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return BaseResults.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUserModel sysUser = sysUserConfigService.getUserByLoginName(request.getLoginName());
        if (null != sysUser){
            return BaseResults.error("账号已经存在");
        }

        SysUserModel sysUserModel = CopyUtils.copies(request,new SysUserModel());
        sysUserConfigService.saveUser(sysUserModel);
        return BaseResults.success(null);
    }

    @GetMapping("/logout")
    public BaseResults logout(HttpServletRequest request) {
        CurrentUser.remove();
        request.getSession().removeAttribute(sessionService.USER_SESSION_KEY);
        return BaseResults.success(null);
    }

    /**
     * 统计登录用户
     * @param request
     * @return
     */
    @GetMapping("/sessions")
    public BaseResults getSessions(HttpServletRequest request) {
        Map<String, SysUserModel> s = sessionService.getAllUserToken();
        SessionUserResp resp = new SessionUserResp();
        if (s!= null) {
            resp.setSessionUsers(new ArrayList<>(s.values()));
        }
        return BaseResults.success(resp);
    }

}
